import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/apis/user/index';
import type { loginFormData, loginResponseData, userInfoReponseData } from "@/apis/user/type";

export const useUserStore = defineStore('User', () => {
    let token = ref(localStorage.getItem('TOKEN'))
    //UserInfo
    const username = ref('')
    const avatar = ref('')

    //用户登录的方法
    const userLogin = async (data: loginFormData) => {
        let res: loginResponseData = await reqLogin(data);
        if (res.code == 200) {
            token.value = res.data
            //本地存储持久化存储一份
            localStorage.setItem('TOKEN', res.data)
            return 'ok';
        } else {
            return Promise.reject(res);
        }
    }

    //获取用户信息方法
    const userInfo = async () => {
        let res: userInfoReponseData = await reqUserInfo();
        // console.log(res);
        if (res.code == 200) {
            username.value = res.data.name
            avatar.value = res.data.avatar
            return Promise.resolve(res.data);
        } else {
            return Promise.reject(res);
        }
    }

    //退出登录
    const userLogout = async () => {
        //退出登录请求
        let res: any = await reqLogout();
        if (res.code == 200) {
            //目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
            token.value = ''
            username.value = ''
            avatar.value = ''
            localStorage.clear()
            return Promise.resolve(res)
        } else {
            return Promise.reject(res)
        }

    }


    return { token, username, avatar, userLogin, userInfo, userLogout }
})
